/**
 * DoubleBits.java
 * @author: liuex
 * 2008-3-12 ����06:29:43
 *
 * note: 
 */
package org.lex.math;

/**
 * 
 */
public class DoubleBits {
	private double val = 0D;
	private long sign = 0L;
	private long exponent = 0L;
	private long mantissa = 0L;
	private double mantissaDouble = 0D;
	private static long[] bits = new long[52];
	private static double[] values = new double[52];
	static {
		for (int i = 0; i < 52; i++) {
			bits[i] = 1L << (51 - i);
			values[i] = java.lang.Math.pow(2, -i - 1);
		}
	}

	public static void main(String[] args) {
		double[] src = { 1.5d, -1.5d, 0.5, -0.5, 5, -5, java.lang.Math.PI, java.lang.Math.E };
		for (int i = 0; i < src.length; i++) {
			DoubleBits d = new DoubleBits(src[i]);
			System.out.println(d.toString());
		}
	}

	public DoubleBits(double val) {
		this.val = val;
		long bits = Double.doubleToRawLongBits(val);
		this.sign = (bits & 0x8000000000000000L) >> 63;
		this.exponent = ((bits & 0x7ff0000000000000L) >> 52);
		int n = Long.bitCount(this.exponent);
		if (0 == n || 8 == n)
			this.mantissaDouble = 0d;
		else
			this.mantissaDouble = 1d;
		this.exponent -= 1023L;
		this.mantissa = bits & 0x000fffffffffffffL;
		for (int i = 0; i < 52; i++) {
			long b = (DoubleBits.bits[i] & this.mantissa) >> (51 - i);
			mantissaDouble += b * values[i];
		}
	}

	public String toString() {
		StringBuilder buf = new StringBuilder();
		buf.append(val).append(" = ");
		if (-1L == sign)
			buf.append('-');
		buf.append(this.mantissaDouble).append(" x 2^");
		buf.append(this.exponent);
		return buf.toString();
	}
}
